package com.itcam.phaselist.collection_;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


/**
 * 迭代器（Iterator）<p>
 * 1.Iterator对象称为迭代器，主要用于遍历Collection集合中的元素<p>
 * 2.所有实现了Colletcion接口的集合都有一个iterator()方法，用以返回一个实现了Itreatoor接口的对象，即可以返回一个迭代器<p>
 * 3.Iterator仅用于遍历集合，Iterator本身不存放对象<p>
 * <p>
 * 注意：调用iterator.next()方法之前必须要调用iterator.hasNext()进行检测。
 * 若不调用，且下一条记录无效，直接调用iterator.next()会抛出NoSuchElementException异常
 */
public class CollectionIterator {
    public static void main(String[] args) {
        Collection col = new ArrayList();

        col.add(new Book("三国演义", "罗贯中", 10.1));
        col.add(new Book("小李飞刀", "古龙", 5.1));
        col.add(new Book("红楼梦", "曹雪芹", 34.6));

//        System.out.println(col);

        // 遍历col集合
        // 1.先得到col对应的迭代器
        Iterator iterator = col.iterator();
        // 2.使用while循环遍历 ==>itit(快速生成while)
        while (iterator.hasNext()) { // 判断是否还有数据
            // 返回下一个元素，类型是Object
            Object obj = iterator.next();
            System.out.println("obj = " + obj.toString());
        }
        // 3.当退出while循环后，这时iterator迭代器指向最后的元素
        // 4.如果要再次遍历，需要重置迭代器
        iterator = col.iterator();
        System.out.println("第二次遍历");
//        while (iterator.hasNext()) {
//            Object obj = iterator.next();
//            System.out.println("obj = " + obj.toString());
//        }
        // 增强for循环遍历
        for (Object obj : col) {
            System.out.println("obj = " + obj.toString());
        }

    }
}

class Book {
    private String name;
    private String author;
    private double price;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
